package com.szl.yeb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szl.yeb.entity.Menu;
import com.szl.yeb.mapper.MenuMapper;
import com.szl.yeb.mapper.MenuRoleMapper;
import com.szl.yeb.entity.MenuRole;
import com.szl.yeb.service.MenuRoleService;
import com.szl.yeb.utils.AdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.szl.yeb.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szl.yeb.utils.MybatisPlusUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (MenuRole)表服务实现类
 *
 * @author szl
 * @since 2022-08-27 11:00:57
 */
@Service("menuRoleService")
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements MenuRoleService {

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageResult getPage(Integer currentPage, Integer size, MenuRole menuRole) {
        Page<MenuRole> page = new Page<>(currentPage, size);

        QueryWrapper<MenuRole> queryWrapper = MybatisPlusUtil.queryWrapperBuilder(menuRole);

        this.page(page, queryWrapper);

        return new PageResult((int) page.getTotal(), page.getRecords());
    }

    @Override
    @Transactional
    public Integer updateMenuRoleAssociations(Integer rid, List<Integer> mids) {

        if (!mids.isEmpty()) {

            List<Map<String, Object>> maps = menuMapper.selectMaps(MybatisPlusUtil.getLQWrapper(Menu.class)
                    .select(Menu::getParentId).in(Menu::getId, mids));

            Set<Integer> ids = maps.stream().map(item -> (Integer) item.get("parentId")).collect(Collectors.toSet());

            mids.addAll(ids);
        }

        baseMapper.delete(MybatisPlusUtil.getLQWrapper(MenuRole.class).eq(MenuRole::getRid, rid));

        if (mids.isEmpty()) {

            Integer adminId = AdminUtil.getCurrentAdmin().getId();
            redisTemplate.delete("menu_" + adminId);

            //返回1代表已清空该角色菜单
            return 1;
        }

        Integer result = menuRoleMapper.insertMenuRoleAssociations(rid, mids);

        Integer adminId = AdminUtil.getCurrentAdmin().getId();
        redisTemplate.delete("menu_" + adminId);

        return result;
    }
}

